package cn.chiship.framework.third.biz.all.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.common.util.FrameworkUtil2;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfigExample;
import cn.chiship.framework.third.biz.all.mapper.ThirdApplicationKeyConfigMapper;
import cn.chiship.framework.third.biz.all.service.ThirdCacheService;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.framework.third.core.common.WechatUtils;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.constants.CacheConstants;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lijian
 */
@Service
public class ThirdCacheServiceImpl implements ThirdCacheService {
    @Resource
    private RedisService redisService;
    @Resource
    private ThirdApplicationKeyConfigMapper applicationKeyConfigMapper;

    @Override
    public ThirdApplicationKeyConfig getConfigByAppId() {
        return getConfigByAppId(ThirdUtil.getAppId());
    }

    @Override
    public ThirdApplicationKeyConfig getConfigByAppId(String appId) {
        String key = CommonCacheConstants.buildKey(CacheConstants.REDIS_THIRD_CONFIG_PREFIX);
        if (!redisService.hHasKey(key, FrameworkUtil2.getGlobalProperties().getId() + "-" + appId)) {
            throw new BusinessException("没有找到对应的appId");
        }
        return (ThirdApplicationKeyConfig) redisService.hget(key, FrameworkUtil2.getGlobalProperties().getId() + "-" + appId);
    }

    @Override
    public void cacheConfig() {
        String key = CommonCacheConstants.buildKey(CacheConstants.REDIS_THIRD_CONFIG_PREFIX);
        redisService.del(key);
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria().andProjectIdEqualTo(FrameworkUtil2.getGlobalProperties().getId());
        List<ThirdApplicationKeyConfig> applicationKeyConfigs = applicationKeyConfigMapper.selectByExample(applicationKeyConfigExample);

        for (ThirdApplicationKeyConfig config : applicationKeyConfigs) {
            redisService.hset(key, FrameworkUtil2.getGlobalProperties().getId() + "-" + config.getAppId(), config);
        }
    }
}
